<?php
namespace app\api\controller;

use app\api\model\Order as OrderModel;
use app\api\model\OrderDetail;
use app\service\WebSocketService;
use think\facade\Request;
use Workerman\Connection\TcpConnection;

class Order
{
    protected $webSocketService;
    public function __construct()
    {
        $this->webSocketService = new WebSocketService();
    }
    
    public function index()
    {
        $dishes = OrderModel::select();
        return json(['code' => 200, 'data' => $dishes]);
    }
    
    public function store()
    {
        $data = Request::post();
        $order = new OrderModel();
        $order->user_id = 1;//$data['user_id'];
        $order->save();

        foreach ($data['dishes'] as $dish) {
            $orderDetail = new OrderDetail();
            $orderDetail->order_id = $order->id;
            $orderDetail->dish_id = $dish['id'];
            $orderDetail->quantity = $dish['quantity'];
            $orderDetail->save();
        }

        $this->webSocketService->pushOrderStatus($order);

        return json(['code' => 200, 'message' => '订单创建成功']);
    }

    public function updateStatus()
    {
        $data = Request::post();
        $order = OrderModel::find($data['id']);
        $order->status = $data['status'];
        $order->save();
        // 实时推送订单状态更新
        $this->webSocketService->pushOrderStatus($order);

        return json(['code' => 200, 'message' => '订单状态更新成功']);
    }
    
}
